$(() => {
    layui.use('layer', function () {
        let layer = layui.layer;

        // 点击验证码图片刷新
        // $('#captchaImg').on('click', function () {
        //     this.src = '/shopping/captcha.jpg?t=' + new Date().getTime(); // 防止缓存
        // });

        $("#login").click(function (e) {
            e.preventDefault(); // 防止表单默认提交行为

            let phone = $("#phone").val().trim();
            let password = $("#password").val().trim();
            // let captcha = $("#captcha").val().trim();

            if (phone === '') {
                layer.msg('手机号不能为空', {icon: 5, anim: 6});
                return;
            }
            if (password === '') {
                layer.msg('密码不能为空', {icon: 5, anim: 6});
                return;
            }
            // if (captcha === '') {
            //     layer.msg('验证码不能为空', {icon: 5, anim: 6});
            //     return;
            // }

            $.ajax({
                url: ctx + "/shopping/member/login",
                method: "post",
                dataType: "json",
                data: {
                    phone,
                    password,
                    // captcha
                },
                success: function (resp) {
                    if (resp!=null) {
                        console.log("1111111111"+ resp.data)
                        const member = resp.data;
                        if (member && member.id) {
                            // ✅ 将 userId 存入全局变量和 localStorage
                            window.currentUserId = member.id;
                            localStorage.setItem("currentUserId", member.id);
                        }

                        // 跳转首页
                        window.location.href = '/shopping/index';
                    } else {
                        layer.msg(resp.error, {icon: 5, anim: 6});
                        // $('#captchaImg').click(); // 刷新验证码
                    }
                },
                error: function () {
                    layer.msg("操作失败", {icon: 5, anim: 6});
                    // $('#captchaImg').click();
                }
            });
        });
    });
});
